package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.core.BasicController;
import cn.net.isir.core.SetBasicService;
import cn.net.isir.entity.*;
import cn.net.isir.service.*;
import cn.net.isir.utils.JSONUtils;
import cn.net.isir.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author liuxubo
 * @filename OrganizationController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/02/22
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/org")
public class OrganizationController extends BasicController<Organizations> {
    @SetBasicService
    @Resource
    private OrganizationsService organizationsService;
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private UserService userService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserOrgService userOrgService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private MessageService messageService;

    @Override
    public ResultObject edit(@RequestBody Map map) {
        Organizations organizations = JSONUtils.toEntityObject(map, Organizations.class);
        List<Organizations> list = organizationsService.selectList(null);
        for (Organizations org : list) {
            if (org.getId().equals(organizations.getId())) {
                continue;
            }
            // 判断同一个父级组织机构下，是否已有相同名字
            if (org.getOrgName().equals(organizations.getOrgName())) {
                if (org.getPid().equals(organizations.getPid())) {
                    return new ResultObject(501, "has same name in the parent org.", null);
                }
            }
            // 判断是否已有组织机构编码，如果已有，则返回错误信息
            if (org.getOrgCode().equals(organizations.getOrgCode())) {
                return new ResultObject(502, "has same code.", null);
            }
        }
        return super.edit(map);
    }

    /**
     * 增加信息
     *
     * @param map 增加信息
     * @return 结果
     */
    @Override
    public ResultObject add(@RequestBody Map map) {
        Organizations organizations = JSONUtils.toEntityObject(map, Organizations.class);
        // 获取组织机构列表
        List<Organizations> list = organizationsService.selectList(null);
        for (Organizations org : list) {
            // 判断同一个父级组织机构下，是否已有相同名字
            if (org.getOrgName().equals(organizations.getOrgName())) {
                if (org.getPid().equals(organizations.getPid())) {
                    return new ResultObject(501, "has same name in the parent org.", null);
                }
            }
            // 判断是否已有组织机构编码，如果已有，则返回错误信息
            if (org.getOrgCode().equals(organizations.getOrgCode())) {
                return new ResultObject(502, "has same code.", null);
            }
        }
        int result = organizationsService.insert(organizations);
        return new ResultObject(200, "success", result);
    }

    /**
     * 删除信息
     *
     * @param id 主键
     * @return 结果
     */
    @Override
    public ResultObject delete(@PathVariable String id) {
        int result = organizationsService.delete(id);
        List<Message> messageList = messageService.findMsgListByOrgId(id);
        for (Message m : messageList) {
            // 如果没有组织机构，则跳过本次循环
            if (StringUtils.isBlank(m.getOrgIds())) {
                continue;
            }
            StringBuilder sb = new StringBuilder();
            String[] idArr = m.getOrgIds().split(",");
            if (idArr.length >= 2) {
                for (String s : idArr) {
                    if (!s.equals(id)) {
                        sb.append(s).append(",");
                    }
                }
            }
            String orgIds = "";
            if (sb.length() > 0) {
                orgIds = sb.substring(0, sb.length() - 1);
            }
            m.setOrgIds(orgIds);
            messageService.update(m);
        }
        UserOrg userOrg = new UserOrg();
        userOrg.setUserId(id);
        List<Organizations> userOrgList = crmUserManagerService.getOrgListByOrgId(id);
        // 加入本身组织机构
        Organizations o = new Organizations();
        o.setId(id);
        userOrgList.add(o);
        // 执行删除操作
        userOrgService.deleteUserByOrgList(userOrgList);
        return new ResultObject(200, "success", result);
    }

    @RequestMapping(value = "/empList", method = RequestMethod.GET)
    public ResultObject getEmpList(String orgId, Integer pageNo, Integer pageSize) {
        Set<String> userIds = crmUserManagerService.getSalesmanIdByOrgId(orgId);
        StringBuilder sb = new StringBuilder();
        userIds.forEach(i -> sb.append(i).append(","));
        String ids = null;
        if (sb.length() > 0) {
            ids = sb.substring(0, sb.length() - 1);
        }
        if (ids == null) {
            return new ResultObject(200, "success", new PageInfo<>());
        }
        User user = new User();
        user.setIds(ids);
        PageInfo<User> pageInfo = userService.selectPageList(user, pageNo, pageSize);
        JSONObject jo = JSONObject.parseObject(JSON.toJSONString(pageInfo));
        JSONArray ja = new JSONArray();
        for (User u : pageInfo.getList()) {
            JSONObject jsonObject = JSONUtils.toJSONObject(userInfoService.selectByUserId(u.getId()));
            List<Role> roleList = roleService.selectListByUser(u);
            if (roleList != null && roleList.size() > 0) {
                jsonObject.put("roleName", roleList.get(0).getRoleName());
            }

//            UserRole ur = new UserRole();
//            ur.setUserId(u.getId());
//            UserRole userRole = userRoleService.selectOne(ur);
//            Role role = new Role();
//            role.setId(userRole.getRoleId());
//            Role role_new = roleService.selectOne(role);
//            jsonObject.put("roleName",role_new.getRoleName());
            ja.add(jsonObject);
        }
        jo.put("list", ja);
        return new ResultObject(200, "success", jo);
    }
}
